package com.opennetexam.manager.controller;

import com.opennetexam.manager.bussinessservice.BeforeExamService;
import com.opennetexam.manager.common.CommonFunction;
import com.opennetexam.manager.common.OperationResult;
import com.opennetexam.manager.databasemodel.ExamSubject;
import com.opennetexam.manager.databasemodel.Examinee;
import com.opennetexam.manager.databasemodel.ExamineeArrange;
import com.opennetexam.manager.dto.*;
import com.opennetexam.manager.enums.*;
import com.opennetexam.manager.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.UnknownHostException;
import java.util.*;

/**
 * 客户端  考生考试模块
 */
@Controller
@RequestMapping("Examinee")
public class ExamineeController extends BaseController {

    @Autowired
    private BeforeExamService beforeExamService;

    @Value("${spring.profiles.active}")
    private String profile;

    //公共key
    private String tokenKey = "token";
    private String viewBagKey = "viewBag";

    /**
     * 视图 - 下载客户端页
     *
     * @return
     */
    @RequestMapping(value = "/DownloadApp", method = RequestMethod.GET)
    public String toDownloadApp(HttpServletRequest request, Model model) {
        model.addAttribute("profile", profile);
        return "examinee/DownloadApp";
    }

    /**
     * 视图 - 登录页
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/Login", method = RequestMethod.GET)
    public String toLogin(HttpServletRequest request, Model model) throws UnknownHostException {
        //获取当前客户端IP
        String hostAddress = NetworkUtils.getLocalIp(request);
        //根据当前客户端的IP尝试获取座位号
        String seatNo = beforeExamService.getSeatNo(hostAddress).toString();
        model.addAttribute("seatNo", seatNo);
        model.addAttribute("profile", profile);
        return "examinee/Login";
    }

    /**
     * 视图 - 完成页
     *
     * @return
     */
    @RequestMapping(value = "/CompletionPage", method = RequestMethod.GET)
    public String completionPage() {
        return "examinee/CompletionPage";
    }

    /**
     * 视图 - 科目列表页
     *
     * @param model
     * @param token
     * @return
     */
    @RequestMapping(value = "/Examlist", method = RequestMethod.GET)
    public String toExamlist(Model model, String token) {
        model.addAttribute(tokenKey, token);
        return "examinee/Examlist";
    }

    /**
     * 视图 - 下载试卷页
     *
     * @param token     key
     * @param planId    计划标识
     * @param appId     主办方标识
     * @param subjectId 科目标识
     * @return
     */
    @RequestMapping(value = "/DownloadPaper", method = RequestMethod.GET)
    public String downloadPaper(HttpServletRequest request, Model model, String token, String planId, String appId, String subjectId) throws UnknownHostException {
        //获取当前客户端IP
        String hostAddress = "";
        //机考获取IP
        if (PatternUtil.getPatternSplit(token, ":").size() == 1) {
            hostAddress = NetworkUtils.getLocalIp(request);
        }

        //不区分模拟和正式
        DownloadPaperVo formalUnifiedExam = beforeExamService.getFormalUnifiedExam(token, appId, planId, subjectId, hostAddress);
        model.addAttribute(viewBagKey, formalUnifiedExam);
        return "examinee/DownloadPaper";
    }

    /**
     * 视图 - 人脸识别页
     *
     * @return
     */
    @RequestMapping(value = "/FaceCompare", method = RequestMethod.GET)
    public String faceCompare(Model model, String token) {
        FaceCompareExamineeInfoVo faceCompareExamineeInfoVo = beforeExamService.getFaceCompareExamineeInfo(token);
        model.addAttribute(viewBagKey, faceCompareExamineeInfoVo);
        model.addAttribute(tokenKey, token);
        return "examinee/FaceCompare";
    }

    /**
     * 视图 - 承诺书
     *
     * @return
     */
    @RequestMapping(value = "/Promise", method = RequestMethod.GET)
    public String promise(Model model, String token) {
        PromiseExamineeInfoVo promiseExamineeInfoVo = beforeExamService.getPromiseExamineeInfo(token);
        model.addAttribute(tokenKey, token);
        model.addAttribute(viewBagKey, promiseExamineeInfoVo);
        return "examinee/Promise";
    }

    /**
     * 视图 - 考试须知页
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/ExamNotice", method = RequestMethod.GET)
    public String examNotice(Model model, String token) {
        ExamNoticeVo examNoticeResult = beforeExamService.getExamNoticeResult(token);
        model.addAttribute(viewBagKey, examNoticeResult);
        return "examinee/ExamNotice";
    }

    /**
     * 视图 - 预览页
     *
     * @param model
     * @param token
     * @return
     */
    @RequestMapping(value = "/Respondence", method = RequestMethod.GET)
    public String respondence(Model model, String token) {
        model.addAttribute(viewBagKey, beforeExamService.getExam(token));
        return "examinee/Respondence";
    }

    /**
     * 视图 - 答题页
     *
     * @param model
     * @param token
     * @return
     */
    @RequestMapping(value = "/ExamPaper", method = RequestMethod.GET)
    public String examPaper(Model model, String token) {
        model.addAttribute(viewBagKey, beforeExamService.getExam(token));
        return "examinee/ExamPaper";
    }

    /**
     * 保存考生照片
     *
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/SaveExamineePhoto", method = RequestMethod.POST)
    public void savePhoto(@RequestBody Map<String, Object> requestBody, HttpServletResponse response) {
        OperationResult operationResult;

        try {
            String token = (String) requestBody.get("token");
            Integer type = (Integer) requestBody.get("type");
            String data = (String) requestBody.get("data");

            operationResult = beforeExamService.saveExamineePhoto(token, type, data);
        } catch (Exception e) {
            e.printStackTrace();
            operationResult = new OperationResult(OperationResultType.Error, OperationResultType.Error.getDisplay());
        }

        CommonFunction.responseWrite(response, operationResult);
    }

    /**
     * 获取科目列表（正式和模拟）
     *
     * @param token    key
     * @param response
     */
    @RequestMapping(value = "/GetSubjectList", method = RequestMethod.GET)
    public void getSubjectList(String token, HttpServletResponse response) {
        //正式
        Integer formal = ExamPlanApplicationRange.Formal.getPrefix();
        //模拟
        Integer mock = ExamPlanApplicationRange.Mock.getPrefix();
        //正式科目列表
        List<ExamineePlanInfo> formalList = beforeExamService.getAnyTimeExam(token, formal);
        //模拟科目列表
        List<ExamineePlanInfo> mockList = beforeExamService.getAnyTimeExam(token, mock);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("formalList", formalList);
        resultMap.put("mockList", mockList);
        CommonFunction.responseWrite(response, resultMap);
    }

    /**
     * 验证指定准考证号和证件号是否正确
     *
     * @param examCardNo 准考证号
     * @param idCardNo   证件号码
     * @return
     */
    @RequestMapping(value = "/CheckIdCard", method = RequestMethod.POST)
    @ResponseBody
    public boolean checkIdCard(HttpServletRequest request, String examCardNo, String idCardNo) throws UnknownHostException {
        //获取当前客户端IP
        String hostAddress = NetworkUtils.getLocalIp(request);

        examCardNo = examCardNo.trim();
        idCardNo = idCardNo.trim();
        if (beforeExamService.checkIdCard(examCardNo, idCardNo)) {
            //LoginRecord.saveLoginRecord(examCardNo, hostAddress);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 解锁验证证件号是否正确
     *
     * @param token    key
     * @param idCardNo 证件号码
     * @return
     */
    @RequestMapping(value = "/CheckIdCardForUnLock", method = RequestMethod.POST)
    @ResponseBody
    public boolean checkIdCardForUnLock(String token, String idCardNo) {
        //获取缓存数据
        ClientLoginModel clientLoginModel = beforeExamService.getEhCacheValue(token);
        Examinee examinee = clientLoginModel.getExaminee();

        String examCardNo = examinee.getExamCardNo().trim();
        idCardNo = idCardNo.trim();
        return beforeExamService.checkIdCard(examCardNo, idCardNo);
    }

    /**
     * 判断科目是否签到
     *
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/IsSignSubject", method = RequestMethod.POST)
    public void isSignSubject(@RequestBody Map<String, Object> requestBody, HttpServletResponse response) {
        String token = (String) requestBody.get(tokenKey); //key
        String appId = (String) requestBody.get("appId"); //主办方标识
        String planId = String.valueOf(requestBody.get("planId"));//计划标识
        String subjectId = (String) requestBody.get("subjectId");//科目标识

        boolean isSign = beforeExamService.isSignSubject(token, appId, planId, subjectId);
        CommonFunction.responseWrite(response, isSign);

    }


    /**
     * 获取学生信息
     *
     * @param token    key
     * @param response
     */
    @RequestMapping(value = "/getExamineeInfo", method = RequestMethod.GET)
    public void getExamineeInfo(String token, HttpServletResponse response) {
        CommonFunction.responseWrite(response, beforeExamService.getExamineeInfo(token));
    }

    /**
     * 获取考试试卷数据，返回给前端
     *
     * @param token
     * @param response
     */
    @RequestMapping(value = "/GetExamPaper", method = RequestMethod.GET)
    public void getExamPaper(String token, HttpServletResponse response) {
        Map<String, Object> resultMap = beforeExamService.getExamPaper(token);
        CommonFunction.responseWrite(response, resultMap);
    }


    /**
     * 获取须知页倒计时
     *
     * @param token key
     */
    @RequestMapping(value = "/GetExamTime", method = RequestMethod.GET)
    public void getExamTime(String token, HttpServletResponse response) {
        //获取缓存
        ClientLoginModel clientLoginModel = beforeExamService.getEhCacheValue(token);
        ExamineeArrange examineeArrange = clientLoginModel.getExamArrange();
        //开考时间
        Date planBeginTime = DateUtil.convertStringToDate(examineeArrange.getPlanBeginTime());
        //当前时间
        Date dateNow = new Date();
        //获取两个时间差  planBeginTime - dateNow
        Long timeDifference = DateUtil.getTimeDifference(planBeginTime, dateNow);
        CommonFunction.responseWrite(response, timeDifference.toString());
    }

    /**
     * 获取提前显示试卷时长
     *
     * @param token
     */
    @RequestMapping(value = "/GetPreviewPaperTime", method = RequestMethod.GET)
    public void getPreviewPaperTime(String token, HttpServletResponse response) {
        //获取缓存
        ClientLoginModel clientLoginModel = beforeExamService.getEhCacheValue(token);
        ExamSubject subject = clientLoginModel.getExamSubject();
        CommonFunction.responseWrite(response, subject.getPreviewPaperTime().toString());
    }

    /**
     * 获取考试期间时间
     *
     * @param token
     * @param response
     */
    @RequestMapping(value = "/GetTime", method = RequestMethod.GET)
    public void getTime(String token, HttpServletResponse response) {
        ExamPeriodTimeVo examPeriodTimeVo = beforeExamService.getTime(token);
        CommonFunction.responseWrite(response, examPeriodTimeVo);
    }

    /**
     * 保存单题作答结果
     *
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/SaveQuestionAnswer", method = RequestMethod.POST)
    public void saveQuestionAnswer(HttpServletRequest request, @RequestBody Map<String, Object> requestBody, HttpServletResponse response, String token) throws UnknownHostException {

        //获取当前客户端IP
        String hostAddress = NetworkUtils.getLocalIp(request);

        List<ExamineeAnswerDetailViewModel> answerList = new ArrayList<>();
        ExamineeAnswerDetailViewModel examineeAnswerDetailViewModel = new ExamineeAnswerDetailViewModel();
        examineeAnswerDetailViewModel.setMarked((Boolean) requestBody.get("isMarked"));
        examineeAnswerDetailViewModel.setIsCompletion((Integer) requestBody.get("isCompletion"));
        examineeAnswerDetailViewModel.setExamPaperItemId((String) requestBody.get("examPaperItemId"));
        examineeAnswerDetailViewModel.setExamPaperID((String) requestBody.get("examPaperInfoId"));
        examineeAnswerDetailViewModel.setSequenceIndex((Integer) requestBody.get("sequenceIndex"));
        examineeAnswerDetailViewModel.setAnswerResults((List<String>) requestBody.get("answerResults"));

        answerList.add(examineeAnswerDetailViewModel);
        SaveAnswerVo saveAnswerVo = beforeExamService.saveAnswer(token, answerList, hostAddress);
        CommonFunction.responseWrite(response, saveAnswerVo);
    }

    /**
     * 提交试卷，清空cache
     *
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/SubmitPaper", method = RequestMethod.POST)
    public void submitPaper(@RequestBody Map<String, Object> requestBody, HttpServletResponse response) {
        String token = (String) requestBody.get(tokenKey); //key
        Integer submitType = (Integer) requestBody.get("submitType");//交卷类型：0未交卷；1考生自行交卷；2考生试卷导入；3系统自动交卷；4强制交卷
        boolean isMandatory = false;
        //强制交卷 4
        if (submitType.equals(TestPaperSubmitType.CompellentSubmit.getPrefix())) {
            isMandatory = (boolean) requestBody.get("isMandatory");
        }
        OperationResult operationResult = beforeExamService.submitPaper(token, submitType, isMandatory);
        CommonFunction.responseWrite(response, operationResult);
    }
}